<script setup lang="ts">
import { useResizeObserver } from "@vueuse/core";
import { computed, onMounted, type Ref, ref, watch } from "vue";
import { useAppStoreHook } from "@/store/modules/app";
import {
  delay,
  type EchartOptions,
  useDark,
  useECharts,
  UtilsEChartsOption
} from "@pureadmin/utils";
import { defaultChartOption } from "@/views/monitor/components/DefaultConfig";
import { getInstanceData } from "@/api/LabInstanceApi";
import { ElMessage } from "element-plus";
import { Experiment } from "@/api/LabExperimentApi";

const { isDark } = useDark();
const theme: EchartOptions["theme"] = computed(() => {
  return isDark.value ? "dark" : "default";
});

const lineChartRef = ref<HTMLDivElement | null>(null);

const props = defineProps({
  labExperimentData: {
    type: Object as () => Experiment
  },
  expState: {
    type: Number
  }
});

// const defaultPointsNum = 800;
const dataZoomStart = ref(0);
const dataZoomEnd = ref(100);
const chartOption = ref(JSON.parse(JSON.stringify(defaultChartOption)));
// const settingRef = ref(defaultSetting);
// settingRef.value = JSON.parse(JSON.stringify(props.settingLine));

const { setOptions, getInstance, resize } = useECharts(
  lineChartRef as Ref<HTMLDivElement>,
  {
    theme
  }
);

const getSeriesData = async () => {
  console.log("getSeriesData");

  chartOption.value.yAxis[0].name = "Y1";
  chartOption.value.yAxis[1].name = "Y2";
  chartOption.value.dataZoom[0].start = dataZoomStart.value;
  chartOption.value.dataZoom[0].end = dataZoomEnd.value;
  setOptions(chartOption.value as UtilsEChartsOption);

  let series = [];
  //遍历labExperimentData，取出sensor的name

  const legend = {
    data: []
  };

  for (const item of props.labExperimentData.sensors) {
    legend.data.push(item.name);
    console.log("item", item);
    try {
      const startTime = new Date(props.labExperimentData.startTime);
      const endTime = new Date(props.labExperimentData.endTime);

      const timeDifferenceInSeconds = Math.floor((endTime - startTime) / 1000);

      const tempData = await getInstanceData({
        expInstId: props.labExperimentData.id,
        devId: item.deviceId,
        duration: timeDifferenceInSeconds,
        period: item.interval
      });

      const regValue = (
        tempData.data as {
          dataPoints: { createTime: string; regValue: number }[];
        }
      ).dataPoints.map(obj => [obj.createTime, obj.regValue]);

      console.log("regValue", regValue);

      if (regValue.length > 0) {
        chartOption.value.yAxis[0].max = null;
      }

      const newData = {
        name: item.name,
        data: regValue.length === 0 ? [[new Date()]] : regValue,
        type: "line",
        showSymbol: false,
        emphasis: {
          focus: "series",
          scale: true
        }
      };
      console.log("newData", newData);

      chartOption.value.yAxis[0].name = tempData.data.mesure || "Y1";
      // if (indexY == 1) {
      //   newData["yAxisIndex"] = 1;
      // }
      series.push(newData);
    } catch (error) {
      console.log(error);
      ElMessage.error("无法获取数据");
    }
  }
  console.log(series);
  if (series.length === 0) {
    legend.data = ["无数据"];
    series = [
      {
        name: "无数据",
        type: "line",
        showSymbol: false,
        emphasis: {
          focus: "series",
          scale: true
        },
        data: [[new Date()]]
      }
    ];
  }

  chartOption.value = { ...chartOption.value, legend, series };
  setOptions(chartOption.value as UtilsEChartsOption);
};

onMounted(() => {
  getInstance()!.on("datazoom", event => {
    if (event.batch) {
      // 在图表内使用鼠标滚轮缩放
      dataZoomStart.value = event.batch[0].start;
      dataZoomEnd.value = event.batch[0].end;
    } else {
      dataZoomStart.value = event.start;
      dataZoomEnd.value = event.end;
    }
  });

  chartOption.value.dataZoom[0].start = dataZoomStart.value;
  chartOption.value.dataZoom[0].end = dataZoomEnd.value;
  chartOption.value.title.text = `历史数据`;

  setOptions(chartOption.value as UtilsEChartsOption);
  getSeriesData();
});

watch(
  () => [dataZoomStart.value, dataZoomEnd.value],
  ([valStart, valEnd]) => {
    chartOption.value.dataZoom[0].start = valStart;
    chartOption.value.dataZoom[0].end = valEnd;
  }
);

watch(
  () => useAppStoreHook().getSidebarStatus,
  () => {
    delay(600).then(() => resize());
  }
);
useResizeObserver(lineChartRef, () => {
  delay(600).then(() => resize());
});
</script>

<template>
  <div>
    <div ref="lineChartRef" style="width: 100%; height: 40vh" />
  </div>
</template>
./hisdataConfig
